<template>
  <div class="visitor-container">
    <!-- 搜索区域 -->
    <div class="header-container">
      <div class="search-toggle-area">
        <el-button class="search-toggle-button" @click="toggleSearchBar">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-form :inline="true" :model="searchForm" class="search-form" :class="{'is-hidden': !showSearchBar}">
          <el-form-item label="访客姓名">
            <el-input v-model="searchForm.name" placeholder="请输入访客姓名" clearable style="width: 180px;" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable style="width: 180px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 操作按钮区域 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleAdd" class="add-visitor-btn"><el-icon><Plus /></el-icon>添加访客</el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete" class="batch-delete-btn"><el-icon><Delete /></el-icon>批量删除</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div v-loading="loading" class="table-container">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <h3>访客列表</h3>
          </div>
        </template>
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          stripe
          @selection-change="handleSelectionChange"
          :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" width="80" align="center" header-align="center" />
          <el-table-column prop="name" label="访客姓名" width="120" align="center" header-align="center">
            <template #default="scope">
              <el-button type="primary" link @click="handleView(scope.row)">{{ scope.row.name }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" width="80" align="center" header-align="center">
            <template #default="scope">
              <span>{{ scope.row.gender === 'M' ? '男' : scope.row.gender === 'F' ? '女' : '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="联系电话" width="150" align="center" header-align="center" />
          <el-table-column prop="id_card" label="身份证号" min-width="180" align="center" header-align="center" />
          <el-table-column prop="created_at" label="创建时间" width="180" align="center" header-align="center" />
          <el-table-column label="操作" width="180" fixed="right" align="center" header-align="center">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
              <el-popconfirm
                title="确认删除该访客信息吗？该操作不可逆！"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row)"
              >
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空数据提示 -->
        <el-empty v-if="tableData.length === 0 && !loading" description="暂无访客数据" class="empty-data-placeholder"></el-empty>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="visitorFormRef"
        :model="visitorForm"
        :rules="visitorFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="访客姓名" prop="name">
          <el-input v-model="visitorForm.name" placeholder="请输入访客姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="visitorForm.gender">
            <el-radio label="M">男</el-radio>
            <el-radio label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="visitorForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="visitorForm.id_card" placeholder="请输入身份证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="访客详情"
      v-model="viewDialogVisible"
      width="700px"
      destroy-on-close
      custom-class="visitor-detail-dialog"
    >
      <div class="visitor-detail-container">
        <div class="visitor-detail-header">
          <div class="visitor-detail-title">
            <h2>{{ visitorDetail.name }}</h2>
          </div>
          <div class="visitor-detail-meta">
            <span v-if="visitorDetail.created_at">创建于 {{ formatDate(visitorDetail.created_at) }}</span>
            <span v-if="visitorDetail.updated_at">最后更新 {{ formatDate(visitorDetail.updated_at) }}</span>
          </div>
        </div>

        <el-divider></el-divider>

        <div class="visitor-detail-content">
          <div class="detail-item">
            <div class="detail-label">性别</div>
            <div class="detail-value">{{ visitorDetail.gender === 'M' ? '男' : visitorDetail.gender === 'F' ? '女' : '未知' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">联系电话</div>
            <div class="detail-value">{{ visitorDetail.phone }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">身份证号</div>
            <div class="detail-value">{{ visitorDetail.id_card }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">访客ID</div>
            <div class="detail-value">{{ visitorDetail.visitor_id }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(visitorDetail)">编辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {
  getVisitorList,
  getVisitorById,
  createVisitor,
  updateVisitor,
  deleteVisitor
} from '@/api/personnel.js'

// 表格数据相关
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
})

// 访客表单
const visitorFormRef = ref(null)
const visitorForm = reactive({
  visitor_id: null,
  name: '',
  gender: 'M',
  phone: '',
  id_card: '',
})

// 表单验证规则
const visitorFormRules = {
  name: [
    { required: true, message: '请输入访客姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  id_card: [
    { required: false, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
}

// 对话框相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const visitorDetail = ref({})

// 搜索栏显示状态
const showSearchBar = ref(false)

const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '添加访客档案' : '编辑访客档案'
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return dateString

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取访客列表数据
const fetchVisitorList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name,
      phone: searchForm.phone
    }
    
    const res = await getVisitorList(params)
    if (res.data && res.data.data && res.data.data.list) {
      tableData.value = res.data.data.list
      total.value = res.data.data.total
    } else {
      console.error("响应数据结构不符合预期:", res.data)
      tableData.value = []
      total.value = 0
      ElMessage.warning('获取访客列表数据格式不正确')
    }
  } catch (error) {
    console.error('获取访客列表失败', error)
    ElMessage.error('获取访客列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchVisitorList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.phone = ''
  currentPage.value = 1
  fetchVisitorList()
}

// 切换搜索栏显示状态
const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchVisitorList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchVisitorList()
}

// 表格选择相关
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 重置表单
const resetVisitorForm = () => {
  if (visitorFormRef.value) {
    visitorFormRef.value.resetFields()
  }
  visitorForm.visitor_id = null
  visitorForm.name = ''
  visitorForm.gender = 'M'
  visitorForm.phone = ''
  visitorForm.id_card = ''
}

// 添加访客
const handleAdd = () => {
  dialogType.value = 'add'
  resetVisitorForm()
  dialogVisible.value = true
}

// 编辑访客
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  resetVisitorForm()
  
  try {
    // 如果是从详情页点击编辑，直接使用已有数据
    if (viewDialogVisible.value) {
      visitorForm.visitor_id = row.visitor_id
      visitorForm.name = row.name
      visitorForm.gender = row.gender || 'M'
      visitorForm.phone = row.phone
      visitorForm.id_card = row.id_card
      viewDialogVisible.value = false
      dialogVisible.value = true
      return
    }

    const res = await getVisitorById(row.visitor_id)
    if (res.data && res.data.data) {
      const visitorData = res.data.data
      visitorForm.visitor_id = visitorData.visitor_id
      visitorForm.name = visitorData.name
      visitorForm.gender = visitorData.gender || 'M'
      visitorForm.phone = visitorData.phone
      visitorForm.id_card = visitorData.id_card
    } else {
      ElMessage.error('获取访客详情数据格式错误')
      return
    }
  } catch (error) {
    console.error('获取访客详情失败', error)
    ElMessage.error('获取访客详情失败')
    return
  }
  
  dialogVisible.value = true
}

// 查看访客详情
const handleView = async (row) => {
  try {
    const res = await getVisitorById(row.visitor_id)
    if (res.data && res.data.data) {
      visitorDetail.value = res.data.data
    } else {
      ElMessage.error('获取访客详情数据格式错误')
      return
    }
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取访客详情失败', error)
    ElMessage.error('获取访客详情失败')
  }
}

// 删除访客
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该访客信息吗？该操作不可逆！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteVisitor(row.visitor_id)
        ElMessage.success('删除成功')
        fetchVisitorList()
      } catch (error) {
        console.error('删除访客失败', error)
        const message = error.response?.data?.message || '删除访客失败'
        ElMessage.error(message)
      }
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的访客')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条访客记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = selectedRows.value.map(item => item.visitor_id)
        for (const id of ids) {
          await deleteVisitor(id)
        }
        ElMessage.success('批量删除成功')
        fetchVisitorList()
      } catch (error)
        {
        console.error('批量删除访客失败', error)
        const message = error.response?.data?.message || '批量删除访客失败'
        ElMessage.error(message)
      }
    })
    .catch(() => {})
}

// 提交表单
const submitForm = () => {
  visitorFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      const formData = { ...visitorForm }
      
      if (dialogType.value === 'add') {
        await createVisitor(formData)
        ElMessage.success('添加成功')
      } else {
        await updateVisitor(formData.visitor_id, formData)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      fetchVisitorList()
    } catch (error) {
      console.error('保存访客信息失败', error)
      const message = error.response?.data?.message || '保存访客信息失败'
      ElMessage.error(message)
    } finally {
      submitLoading.value = false
    }
  })
}

onMounted(() => {
  fetchVisitorList()
})
</script>

<style scoped>
.visitor-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 20px;
  background-color: transparent;
  box-shadow: none;
  border-radius: 10px;
  position: relative;
}

.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-grow: 1;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距，使其更紧凑 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

/* 确保表单项内部的label和input/select水平对齐 */
:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

.action-bar {
  margin-left: 20px;
  flex-shrink: 0;
  align-self: center;
  display: flex;
  gap: 10px;
}

/* Custom style for Add Visitor button to center text and icon */
:deep(.add-visitor-btn),
:deep(.batch-delete-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

/* 表格区域样式 */
.table-container {
  min-height: 400px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

/* 分页区域 */
.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

/* 访客详情样式 */
.visitor-detail-dialog .el-dialog__header {
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
}

.visitor-detail-dialog .el-dialog__body {
  padding: 20px 25px;
}

.visitor-detail-header {
  margin-bottom: 20px;
  text-align: center;
}

.visitor-detail-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 10px;
}

.visitor-detail-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
  font-weight: 700;
}

.visitor-detail-meta {
  display: flex;
  justify-content: center;
  gap: 20px;
  color: #909399;
  font-size: 12px;
}

.el-divider {
  margin: 15px 0;
}

.visitor-detail-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px 15px;
}

.detail-item {
  width: calc(50% - 7.5px);
  margin-bottom: 0;
  padding: 8px 0;
  border-bottom: 1px dashed #e4e7ed;
}

.detail-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 15px;
  color: #303133;
  font-weight: 500;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
/* Primary Button */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}

/* Danger Button */
:deep(.el-button--danger) {
  background-color: rgba(245, 108, 108, 0.1) !important;
  color: #F56C6C !important;
  border-color: rgba(245, 108, 108, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--danger:hover) {
  background-color: rgba(245, 108, 108, 0.15) !important;
  border-color: rgba(245, 108, 108, 0.3) !important;
}

@media screen and (max-width: 768px) {
  .header-container {
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;
  }

  .search-toggle-area {
    width: 100%;
    margin-bottom: 10px;
    justify-content: flex-start;
  }

  .search-form {
    max-width: 100%;
    margin-left: 0;
    padding: 0 10px;
    box-sizing: border-box;
    height: auto;
    min-height: 0;
    flex-wrap: wrap;
  }
  
  .search-form.is-hidden {
    height: 0;
    min-height: 0;
    padding: 0;
  }

  :deep(.search-form .el-form-item) {
    margin-right: 0;
    width: 100%;
    margin-bottom: 10px;
  }

  .action-bar {
    width: 100%;
    margin-left: 0;
    flex-direction: column;
    gap: 10px;
  }

  .action-bar .el-button {
    width: 100%;
  }
  
  .visitor-detail-content {
    flex-direction: column;
    gap: 15px 0;
  }

  .detail-item {
    width: 100%;
  }
}
</style>
